package pers.mine.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import pers.mine.dto.QueryHandler;
import pers.mine.po.Comment;
import pers.mine.po.GoodsGroup;
import pers.mine.po.GoodsItem;
import pers.mine.po.GoodsItemExample;
import pers.mine.po.TopShow;
import pers.mine.service.inter.CommentService;
import pers.mine.service.inter.GoodsGroupService;
import pers.mine.service.inter.GoodsItemService;
import pers.mine.service.inter.GroupShipService;
import pers.mine.service.inter.TopShowService;
import pers.mine.utils.SimpleUtil;
import pers.mine.vo.Info;
import pers.mine.vo.PageInfo;

/**
 * @author Mine
 * @since 2016年10月23日_上午11:25:19
 */
@Controller
@RequestMapping()
@Scope("session")
public class ShowIndexController {
	@Autowired
	GoodsItemService goodsItemService;
	@Autowired
	GroupShipService groupShipService;
	@Autowired
	GoodsGroupService goodsGroupService;
	@Autowired
	CommentService commentService;
	@Autowired
	TopShowService topShowService;

	private Info indexinfo = new Info();// 放到首页的信息

	@RequestMapping(value = "/indexshow")
	// 新首页
	public String newIndex(HttpServletRequest request) throws Exception {
		// 轮换图
		List<TopShow> topShowList = topShowService.findAll();
		// 热卖
		PageInfo<GoodsItem> tempPi = goodsItemService
				.findPageOrderBySUM(QueryHandler.creat()
						.andColumnMark("g_state", "=", "1")
						.andColumnMark("g_num", ">", "0").limitByPageSize(4)
						.set());
		List<GoodsItem> hotList = (tempPi == null) ? null : tempPi
				.getBasePageList();
		// 评价最高
		tempPi = null;
		tempPi = goodsItemService.findPageOrderByGrade(QueryHandler.creat()
				.andColumnMark("g_state", "=", "1")
				.andColumnMark("g_num", ">", "0").limitByPageSize(4).set());
		List<GoodsItem> likeList = (tempPi == null) ? null : tempPi
				.getBasePageList();
		// 最新上架
		tempPi = null;
		tempPi = goodsItemService.findPageOrderBySelveDate(QueryHandler.creat()
				.andColumnMark("g_state", "=", "1")
				.andColumnMark("g_num", ">", "0").limitByPageSize(4).set());
		List<GoodsItem> newList = (tempPi == null) ? null : tempPi
				.getBasePageList();

		// 回显消息
		Info temp = SimpleUtil.getIndexInfoWithSession(request.getSession());
		temp = SimpleUtil.getIndexInfoWithRequest(request);
		if (temp != null) {
			request.setAttribute("indexinfo", temp);
		}
		// 放入
		request.setAttribute("topShowList", topShowList);
		request.setAttribute("hotList", hotList);
		request.setAttribute("likeList", likeList);
		request.setAttribute("newList", newList);
		return "newIndex";
	}

	@RequestMapping(value = "show/{id}")
	public String getEditGoodsInfoPage(@PathVariable("id") Integer id,
			HttpServletRequest req) {
		GoodsItem one = null;
		if (id != null && id > 0) {
			// 获取指定id商品信息
			one = goodsItemService.getOneGoodsItemByID(id);
			if (one != null) {
				// 判断是否有从其Controller转发过来的信息
				if (req.getAttribute("indexinfo") != null) {
					indexinfo = (Info) req.getAttribute("indexinfo");
				} else {
					indexinfo.setType(Info.SUCCESS);
					indexinfo.setMsg("[商品信息查看]:查询#" + id + "编号商品信息成功...");
				}

				// 生成类型字段
				String type = groupShipService.getTypeStr(groupShipService
						.findGroupsByGoodsId(id));
				one.setType(type);
				// 生成商品销量字段
				one.setSale(goodsItemService.findSaleByID(id));
				// 生成平均评价
				one.setGrade(goodsItemService.findGradeByID(id));

				req.setAttribute("oneGoods", one);
				req.setAttribute("indexinfo", indexinfo);
				indexinfo.setCanChange(true);
				return "showOne";
			}
		}
		indexinfo.setType(Info.ERROR);
		indexinfo.setMsg("[商品信息查看]:非法的物品编号...");
		indexinfo.setCanChange(false);
		return "redirect:indexshow";
	}

	/**
	 * 依据关键字返回相关搜索结果
	 * 
	 * @return
	 */
	@RequestMapping(value = "/search")
	public String searchGoods(Integer groupId,// 按分类查询
			String listName,// 查询 热门,最新,评分 ,所有, 未分类等
			String searchType, String keys, // 关键字搜索
			Integer nowPage, Integer pageSize, Integer pageCount// 分页信息
			, HttpServletRequest req) {
		String tip = "搜索页面";
		PageInfo<GoodsItem> pi = null;
		QueryHandler qh = QueryHandler.creat()
				.andColumnMark("g_state", "=", "1")
				.andColumnMark("g_num", ">", "0");
		// 默认页面大小为8
		pageSize = 8;
		if (nowPage == null) {
			nowPage = 1;
		}
		if (pageCount != null && nowPage != null && pageCount < nowPage) {
			nowPage = pageCount;
		}
		qh.limit(nowPage, pageSize);

		// 按分类ID查询
		if (groupId != null) {
			GoodsGroup one = goodsGroupService.findOneById(groupId);
			tip = one == null ? "null" : one.getName() + "&nbsp;分类";
			qh.setNeedWhereWord(false); // 不要Where关键字
			qh.set();
			pi = goodsItemService.findPageByGroupId(groupId, qh);
		}
		// 查询特殊 热门,最新,评分 ,所有, 未分类等
		if (listName != null && !"".equalsIgnoreCase(listName.trim())) {
			listName = listName.toUpperCase();
			switch (listName) {
			case "HOT":
				tip = "热门商品";
				pi = goodsItemService.findPageOrderBySUM(qh.set());
				break;
			case "NEW":
				tip = "新上架商品";
				pi = goodsItemService.findPageOrderBySelveDate(qh.set());
				break;
			case "LIKE":
				tip = "好评商品";
				pi = goodsItemService.findPageOrderByGrade(qh.set());
				break;
			case "NOGROUPSHIP":
				tip = "未分类商品";
				pi = goodsItemService.findPageWithNoGroupShip(qh
						.setNeedWhereWord(false).set());
				break;
			default:// 默认ALL查询所有
				tip = "所有商品";
				pi = goodsItemService.findPageByQueryHandler(qh.set());
				break;
			}
		}
		// 关键字查询
		if ((searchType != null && !"".equals(searchType.trim()))
				|| (keys != null && !"".equals(keys.trim()))) {

			if (keys != null && !"".equals(keys.trim())) {
				// 关键字写回页面
				req.setAttribute("keys", keys);
				tip = "关键字#" + keys + "&nbsp;查询结果";
				if (searchType == null) {
					searchType = "";
				}
				switch (searchType.trim().toUpperCase()) {
				case "ONLYNAME":// 搜索商品名
					tip += "[范围:仅商品名]";
					pi = goodsItemService.findPageByQueryHandler(qh
							.andColumnLike("g_name", keys).set());
					break;
				case "ONLYBRAND":// 搜索品牌
					tip += "[范围:仅商品品牌]";
					pi = goodsItemService.findPageByQueryHandler(qh
							.andColumnLike("g_brand", keys).set());
					break;
				default:// 默认查询 商品名，品牌等..
					tip += "[范围:商品项全局]";
					pi = goodsItemService.findPageByQueryHandler(qh
							.andColumnLikeWithGroup("g_brand", keys)
							// 未测试方法
							.orColumnLike("g_name", keys)
							.orColumnLike("g_msg", keys)
							.orColumnLike("g_desc", keys).endGroup().set());
					break;
				}
			} else {// 查询所有
				tip = "所有商品";
				pi = goodsItemService.findPageByQueryHandler(qh.set());
			}
		}

		// 判断是否有从其Controller转发过来的信息
		if (req.getAttribute("indexinfo") != null) {
			indexinfo = (Info) req.getAttribute("indexinfo");
		}
		if (req.getSession().getAttribute("indexinfo") != null) {
			indexinfo = (Info) req.getAttribute("indexinfo");
		}
		if (indexinfo == null) {
			indexinfo = new Info();
		}
		// 判断是否可以放入信息
		if (indexinfo.isCanChange()) {
			indexinfo.setMsg("搜寻【" + tip + "】结果...");
			if (pi == null) {
				indexinfo.setType(Info.ERROR);
			} else {
				indexinfo.setType(Info.SUCCESS);
			}
		} else {
			indexinfo.setCanChange(true);
		}
		System.out.println(keys);
		req.setAttribute("indexinfo", indexinfo);
		req.setAttribute("tip", tip);

		req.setAttribute("groupId", groupId);

		req.setAttribute("listName", listName);

		req.setAttribute("searchType", searchType);
		req.setAttribute("keys", keys);

		req.setAttribute("goodsPageInfo", pi);
		return "searchPage";
	}

	/**
	 * @param req
	 *            因为可能要获取上一个req参数,所以使用Request
	 * @return
	 */
	@RequestMapping(value = "/oldIndex")
	public String showIndex(Integer nowPage, Integer pageSize,
			Integer pageCount, String keys, HttpServletRequest req) {

		GoodsItemExample exam = new GoodsItemExample();
		// 兼顾排版,默认页面大小为4
		pageSize = 8;
		if (pageCount != null && nowPage != null && pageCount < nowPage) {
			nowPage = pageCount;
		}
		exam.initLimit(nowPage, pageSize);
		if (keys != null && !"".equals(keys.trim())) {
			// 关键字写回页面
			req.setAttribute("keys", keys);
			String keysPro = "%" + keys + "%";
			// 有点麻烦。。。是为了底层selectByExampleForIndex的sql语句动态改变而加入的...
			exam.setiFlag(true);
			// 写死了。。。
			exam.or().andNameLike(keysPro);// 商品名
			exam.or().andTypeLike(keysPro);// 类型
			exam.or().andOriginLike(keysPro);// 产地
			exam.or().andDescLike(keysPro);// 简介
		}
		// 排序方式
		exam.setOrderByClause("g_id,g_name");

		// System.out.println(exam.showBase());
		// 依据筛选条件获取 使用带条件的显示方法
		PageInfo<GoodsItem> pi = goodsItemService
				.findPageByExampleForIndex(exam);
		// System.out.println(pi);
		// 判断是否有从其Controller转发过来的信息
		if (req.getAttribute("indexinfo") != null) {
			indexinfo = (Info) req.getAttribute("indexinfo");
		}
		if (req.getSession().getAttribute("indexinfo") != null) {
			indexinfo = (Info) req.getAttribute("indexinfo");
		}
		if (indexinfo == null) {
			indexinfo = new Info();
		}
		// 判断是否可以放入信息
		if (indexinfo.isCanChange()) {
			indexinfo.setType(Info.SUCCESS);
			if (keys != null && !"".equals(keys.trim())) {
				indexinfo.setMsg("[首页显示]:对于关键字[" + keys + "]查询商品成功...");
			} else {
				indexinfo.setMsg("[首页显示]:查询所有商品成功...");
			}
		} else {
			indexinfo.setCanChange(true);
		}
		System.out.println(keys);
		req.setAttribute("indexinfo", indexinfo);
		req.setAttribute("goodsPageInfo", pi);
		return "shoppingIndex";
	}
}
